package com.owen.liferay.jdo.domain;

import java.util.Date;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Version;
import javax.jdo.annotations.VersionStrategy;

@PersistenceCapable(detachable="true", table="user_")
@Version(column = "modifiedDate", strategy = VersionStrategy.DATE_TIME, extensions = { @Extension(vendorName = "DataNucleus", key = "field-name", value = "modifiedDate") })
public class User {

	
	final static PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");

	@Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
	@PrimaryKey
	private long userId;
	
	@Persistent
	private String screenName;

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public String getScreenName() {
		return screenName;
	}

	public void setScreenName(String screenName) {
		this.screenName = screenName;
	}
	
	@Persistent
	private Date modifiedDate;
	
	public static User findUser(long id) {
		
		System.out.println("findUser is: " + id);

		PersistenceManager pm = PMF.getPersistenceManager();

		Transaction tx = pm.currentTransaction();

		User user = null;
		
		User detached = null;

		try {
			tx.begin();

			user = pm.getObjectById(User.class, id);
			
			detached = pm.detachCopy(user);

			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

		return detached;
	}

}
